﻿using Common.LoadBalancer.Abstractions;
using Common.MefHelp.Attributes; 
using Common.Tools;
namespace Common.SelectService.Select
{
    /// <summary>
    /// consul帮助查询服务
    /// </summary>
    [CustomInjection("consul", typeof(ISelectService))]
    public class ConsulSelectService : ISelectService
    {
        private readonly ILoadBalancerManager _loadBalancerManager;
        /// <summary>
        /// 构造函数
        /// </summary>
        public ConsulSelectService(ILoadBalancerManager loadBalancerManager)
        {
            _loadBalancerManager = loadBalancerManager;
        }

        /// <summary>
        /// 获取Ip和端口
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns></returns>
        public async Task<string?> GetHostAndPortAsync(string serviceName)
        { 
            LoadBalancerMode loadBalancer;
            if (string.IsNullOrWhiteSpace(SelectServiceConfig.Instance?.LoadBalancerType))
            {
                loadBalancer = LoadBalancerMode.RoundRobin;
            }
            else
            {
                loadBalancer = (LoadBalancerMode)Enum.Parse(typeof(LoadBalancerMode), SelectServiceConfig.Instance.LoadBalancerType);
            }
            //获取负载均衡器
            var load = await _loadBalancerManager.Get(serviceName, loadBalancer);
            //获取服务地址
            var result = await load.Lease();
            return result != null ? $"http://{result.Address}:{result.Port}" : string.Empty;

        }
    }
}
